package com.bee.web.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Web请求工具类
 *
 * @author liuzy
 * @since 2015年6月12日
 */
public final class WebUtil {

    public static Map<String, String> getRequestInfo(HttpServletRequest request) {
        String ip = getIpAddr(request);
        String referer = request.getHeader("Referer");
        String userAgent = request.getHeader("User-Agent");
        String cookie = request.getHeader("Cookie");
        String method = request.getMethod();
        String xRequestedWith = request.getHeader("X-Requested-With");//值=null为普通同步请求;值=XMLHttpRequest为AJAX异步请求
        String host = request.getHeader("Host");
        String acceptLanguage = request.getHeader("Accept-Language");
        String acceptEncoding = request.getHeader("Accept-Encoding");
        String accept = request.getHeader("Accept");
        String connection = request.getHeader("Connection");
        Map<String, String> map = new HashMap<String, String>();
        map.put("ip", ip);
        map.put("referer", referer);
        map.put("userAgent", userAgent);
        map.put("cookie", cookie);
        map.put("method", method);
        map.put("xRequestedWith", xRequestedWith);
        map.put("host", host);
        map.put("acceptLanguage", acceptLanguage);
        map.put("acceptEncoding", acceptEncoding);
        map.put("accept", accept);
        map.put("connection", connection);
        return map;
    }

    /**
     * 获取完整请求路径(含内容路径及请求参数)
     *
     * @param request
     * @return
     */
    public static String getRequestURIWithParam(HttpServletRequest request) {
        return request.getRequestURI() + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
    }

    /**
     * 获取ParameterMap
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParamMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> enume = request.getParameterNames();
        while (enume.hasMoreElements()) {
            String name = (String) enume.nextElement();
            map.put(name, request.getParameter(name));
        }
        return map;
    }

    /**
     * @param response
     * @param domain   设置cookie所在域
     * @param path     设置cookie所在路径
     * @param name     cookie的名称
     * @param value    cookie的值
     * @param maxAge   cookie存放的时间(以秒为单位,假如存放三天,即3*24*60*60; 如果值为-1,cookie将随浏览器关闭而清除)
     */
    public static void addCookie(HttpServletResponse response,
                                 String domain, String path,
                                 String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        // 所在域：比如a1.4bu4.com 和 a2.4bu4.com 共享cookie
        if (null != domain && !domain.isEmpty()) {
            cookie.setDomain(domain);
        }
        // 设置cookie所在路径
        cookie.setPath("/");
        if (null != path && !path.isEmpty()) {
            cookie.setPath(path);
        }
        // 设置cookie的过期时间
        if (maxAge > 0) {
            cookie.setMaxAge(maxAge);
        }
        // 添加cookie
        response.addCookie(cookie);
    }

    /**
     * 获取cookie的值
     *
     * @param request
     * @param name    cookie的名称
     * @return
     */
    public static String getCookieValueByName(HttpServletRequest request, String name) {
        Map<String, String> cookieMap = readCookies(request);
        if (cookieMap.containsKey(name)) {
            return cookieMap.get(name);
        } else {
            return null;
        }
    }


    /**
     * 获得所有cookie
     *
     * @param request
     * @return
     */
    public static Map<String, String> readCookies(HttpServletRequest request) {
        Map<String, String> cookieMap = new HashMap<String, String>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (int i = 0; i < cookies.length; i++) {
                String value = cookies[i].getValue();
                value = value.startsWith("%22") ? value.substring(3, value.length() - 3) : value;
                cookieMap.put(cookies[i].getName(), value);
            }
        }
        return cookieMap;
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
